import React, { useState, useRef, useEffect, useImperativeHandle } from "react";
import { Button } from "antd";
import PropTypes from "prop-types";

const SendCode = ({ send, childRef }) => {
    let codeTimer = null;
    const [codeText, setCodeText] = useState(null);
    const [btnDisabled, setBtnDisabled] = useState(false);
    useEffect(() => {
        return () => {
            clearInterval(codeTimer);
            codeTimer = null;
        };
    }, []);
    useImperativeHandle(childRef, () => ({
        init() {
            clearInterval(codeTimer);
            codeTimer = null;
            setCodeText(null);
            setBtnDisabled(false);
        },
    }));
    return (
        <>
            <Button
                disabled={btnDisabled}
                block
                size="large"
                onClick={() => {
                    send().then(res => {
                        setBtnDisabled(true);
                        setCodeText(59);
                        codeTimer = setInterval(() => {
                            setCodeText(oldV => {
                                if (oldV >= 1) {
                                    setCodeText(oldV - 1);
                                } else {
                                    clearInterval(codeTimer);
                                    codeTimer = null;
                                    setBtnDisabled(false);
                                }
                            });
                        }, 1000);
                    }).catch(err=>{})
                }}
            >
                {codeText == null ? "发送验证码" : codeText == 0 ? "重新发送" : `${codeText}s`}
            </Button>
        </>
    );
};
SendCode.propTypes = {
    send: PropTypes.func,
};
SendCode.defaultProps = {
    send: () => {
        console.log("defaultSend");
        return new Promise((resolve, reject) => {
            resolve();
        });
    },
};
export default SendCode;
